package com.yueya.basic.token.model;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.basic.token.service.TokenService;
import com.yueya.common.util.UUIDGenerator;
import com.yueya.config.GlobalParam;

public class Token extends Model<Token> {

	private static final long serialVersionUID = -6985754239540245975L;

	public static Token dao = new Token();
	public static TokenService service = Duang.duang(TokenService.class);

	// 增加token
	@Before(Tx.class)
	public String add(String loginName) {
		String token = null;
		Db.deleteById("t_token", "user_id", loginName);

		Token model = new Token();
		long now = System.currentTimeMillis();
		token = UUIDGenerator.getUUID();
		model.set("token_id", UUIDGenerator.getUUID());
		model.set("user_id", loginName);
		model.set("token", token);
		model.set("expire", now + GlobalParam.getTokenExpire());
		model.save();

		return token;
	}

	// 校验token是否存在，是否超时
	public boolean checkToken(String token) {
		boolean bl = false;
		Record r = Db.findById("t_token", "token", token);
		if (r != null) {
			long now = System.currentTimeMillis();
			if (now < r.getLong("expire")) {
				bl = true;
			}
		}
		return bl;
	}

	public Record getToken(String token) {
		return Db.findById("t_token", "token", token);
	}

}